package reco.db.conf;

import static org.apache.commons.lang.StringUtils.isBlank;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

import org.apache.cayenne.conf.Configuration;
import org.apache.cayenne.conf.ServletUtil;
import org.apache.cayenne.conf.WebApplicationContextFilter;

/**
 * @author juanjo
 */
public class RecoContextFilter extends WebApplicationContextFilter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        final Configuration cayenneConfiguration = ServletUtil.initializeSharedConfiguration(filterConfig.getServletContext());
        setDomainLoaderLoadStrategyWith(filterConfig.getInitParameter("CayenneDomainLoadStrategyClass"));
        RecoDomainLoader.loadCayenneConfiguration(cayenneConfiguration);
    }

    private void setDomainLoaderLoadStrategyWith(String cayenneDomainLoadStrategyClassName) {
        if (isBlank(cayenneDomainLoadStrategyClassName)) {
            throw new IllegalStateException("cayenneDomainLoadStrategyClass was not defined");
        }

        try {
            final Class<?> strategyClass = Class.forName(cayenneDomainLoadStrategyClassName);
            RecoDomainLoader.setLoadStrategy(strategyClass);
        } catch (final ClassNotFoundException e) {
            throw new IllegalArgumentException(cayenneDomainLoadStrategyClassName + " was not found on classpath", e);
        }

    }
}
